package com.dao.impl;

import com.bean.Message;
import com.dao.MessageDAO;
import com.util.C3p0Utils;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class MessageDAOImpl implements MessageDAO {

    /**
     * BeanListHandler将结果列表封装
     * @return
     * @throws SQLException
     */
    @Override
    public List<Message> selectAll() throws SQLException {

        return C3p0Utils.qr.query("select * from message", new BeanListHandler<Message>(Message.class));
    }
    @Override
    public List<Message> selectByName(String userName) throws SQLException {
        return C3p0Utils.qr.query("select * from message  where userName =?", new BeanListHandler<>(Message.class), userName);
    }
    @Override
    public boolean deleteById(Integer id) throws SQLException {
        return C3p0Utils.qr.update("delete from message where id=?", id) > 0;
    }

    @Override
    public boolean insert(Message m) throws SQLException {
        return C3p0Utils.qr.update("insert into message values(null,?,?,?)",m.getUserName(),m.getContent(),m.getTime()) > 0;
    }

    /**
     * ScalarHandler用来将单个Object类型封装
     * @return
     * @throws SQLException
     */
    @Override
    public Integer count() throws SQLException {
        int n = C3p0Utils.qr.query("select count(*) from message", new ScalarHandler<Long>()).intValue();
        return n;
    }
    @Override
    public Integer countSearch(String search) throws SQLException {
        int n = C3p0Utils.qr.query("select count(*) from message where concat(userId,content,time) like ?", new ScalarHandler<Long>(),"%"+search+"%").intValue();
        return n;
    }
    @Override
    public List<Message> selectAllPagination(Integer offset, Integer limit) throws SQLException {
        return C3p0Utils.qr.query("select * from message limit ?,?", new BeanListHandler<>(Message.class), offset, limit);

    }
    @Override
    public List<Message> selectAllPaginationSearch(Integer offset, Integer limit,  String search) throws SQLException {
        return C3p0Utils.qr.query("select * from message where concat(userId,content,time) like ? limit ?,?",
                new BeanListHandler<>(Message.class),"%"+search+"%",offset,limit);

    }
}
